@extends('wechat.member-layout')

@section('head')
    <style>
        #upload-btn {
            margin: 10% auto;
            float: none;
            margin-top: 40%;
            visibility:hidden;
        }
        .moxie-shim:after {
            width: 39.5px;
            height: 2px;
        }
        .moxie-shim:before {
            width: 2px;
            height: 39.5px;
        }
        .moxie-shim {
            border: 1px solid #d9d9d9;
        }
        .moxie-shim:after,
        .moxie-shim:before {
            content: " ";
            position: absolute;
            top: 50%;
            left: 50%;
            -webkit-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
            background-color: #d9d9d9;
        }
    </style>
    <script src="http://{{ env('QINIU_DOMAIN') }}/js/plupload.full.min.js"></script>
    <script src="http://{{ env('QINIU_DOMAIN') }}/js/qiniu.min.js"></script>
    <script src="http://{{ env('QINIU_DOMAIN') }}/js/ajax.min.js"></script>
@endsection

@section('content')
    <div class="container" id="container">
        <div class="weui_uploader_input_wrp" id="upload-btn">
        </div>
        <div class="weui_cells_tips">点击+选择文件上传，文件大小不能超过1024MB</div>
        <div class="weui_cells_tips">可上传图片或视频，只支持jpg、png、mp4、avi、rmvb、wmv、flv、ogv、mkv格式</div>
    </div>
    <div id="loadingToast" class="weui_loading_toast" style="display:none;">
        <div class="weui_mask_transparent"></div>
        <div class="weui_toast">
            <div class="weui_loading">
                <div class="weui_loading_leaf weui_loading_leaf_0"></div>
                <div class="weui_loading_leaf weui_loading_leaf_1"></div>
                <div class="weui_loading_leaf weui_loading_leaf_2"></div>
                <div class="weui_loading_leaf weui_loading_leaf_3"></div>
                <div class="weui_loading_leaf weui_loading_leaf_4"></div>
                <div class="weui_loading_leaf weui_loading_leaf_5"></div>
                <div class="weui_loading_leaf weui_loading_leaf_6"></div>
                <div class="weui_loading_leaf weui_loading_leaf_7"></div>
                <div class="weui_loading_leaf weui_loading_leaf_8"></div>
                <div class="weui_loading_leaf weui_loading_leaf_9"></div>
                <div class="weui_loading_leaf weui_loading_leaf_10"></div>
                <div class="weui_loading_leaf weui_loading_leaf_11"></div>
            </div>
            <p class="weui_toast_content" id="toast">上传中<br><span id="percent">0</span>%</p>
        </div>
    </div>
@endsection

@section('js')
    <script>
        var openid = '{{ Session::get('wechat_openid') }}';
        var uploader = Qiniu.uploader({
            runtimes: 'html5',
            browse_button: 'upload-btn',
            max_file_size : '1024mb',
            filters : {
                max_file_size : '1024mb',
                prevent_duplicates: true,
                // mime_types: [
                //     {title : "Video files", extensions : "avi,mp4"},
                //     {title : "Image files", extensions : "jpeg,jpg,png"},
                // ]
            },
            dragdrop: false,
            chunk_size: 0,//mOxie.Env.OS.toLowerCase()=='windows'?0:'5mb',
            multi_selection: false,
//            resize : {
//                width : 640,
//                quality:100
//            },
            // uptoken_url: '',
            uptoken_func: function(file) {
                console.log('file');
                console.log(file);
                var token='';
                ajax({
                    url:'/wechat/qiniu/upload-token?type='+file._type,
                    async:false,
                    success:function (response) {
                        try {
                            var res = JSON.parse(response);
                            file.key=res.key;
                            token=res.uptoken;
                        } catch(e) {
                        }
                    },
                    error:function (err) {
                    }
                })
                if (!token) {
                    alert('uptoken err');
                }
                return token;
            },
            domain: 'http://{{ env('QINIU_DOMAIN') }}/',
            get_new_uptoken: true,
            // downtoken_url: '/downtoken',
            unique_names: false,
            save_key: false,
            auto_start: true,
            log_level: 2,
            max_retries:2,
            init: {
                'FilesAdded': function(up, files) {
                    console.log(files);
                    var type;
                    if (files[0].type.indexOf('video/') >= 0
                        || files[0].type == 'application/vnd.rn-realmedia-vbr'
                        || files[0].type == 'application/octet-stream'
                        || files[0].type == 'application/video/ogg'
                    ) {
                        type=2;
                    } else if ((/image\/(jpg|jpeg|png)/i).test(files[0].type)) {
                        type=1;
                    } else{
                        alert('type error:'+files[0].type);
                        up.removeFile(files[0]);
                        return;
                    }
                    files[0]._type=type;
                },
                'BeforeUpload': function(up, file) {
                    document.getElementById('loadingToast').style.display='block';
                },
                'UploadProgress': function(up, file) {
                    document.getElementById('percent').innerHTML=file.percent;
                },
                'UploadComplete': function() {
                },
                'FileUploaded': function(up, file, info) {
                    document.getElementById('toast').innerHTML='处理中';
                    try {
                        var info=JSON.parse(info);
                        if (!info.persistentId) {
                            alert('persistentId error');
                            return;
                        }
                        if (file._type==2&&!info.duration) {
                            alert('duration error');
                            return;
                        }
                    } catch(e) {
                        alert('info error');
                        return;
                    }
                    var make=function () {
                        var data={
                            openid:openid,
                            key:file.key,
                            type:file._type
                        };
                        if (file._type==2) {
                            data.duration = encodeURI(info.duration);
                            if (info.duration == null) {
                                data.duration = 0;
                            }
                        }
                        data._token = '{{ csrf_token() }}';
                        ajax({
                            url:'/wechat/qiniu/upload-token?type='+file._type,
                            type:'post',
                            data:data,
                            success:function (response) {
                                try {
                                    var resp=JSON.parse(response);
                                    if (resp.code==1) {
                                        window.location.href=resp.url;
                                    } else {
                                        setTimeout(function () {
                                            get_prefop(resp.persistentId,function () {
                                                window.location.href=resp.url;
                                            });
                                        }, 2000);
                                    }
                                } catch(e) {
                                    alert('make error');
                                }
                            },
                            error:function (err) {
                                alert('make error');
                            }
                        })
                    }
                    var get_prefop=function (id,fun,retries) {
                        retries=retries||1;
                        if (retries>5) {
                            alert('get_prefop error');
                            return;
                        } else {
                            ajax({
                                type:'post',
                                url:'/wechat/qiniu/prefop',
                                data:{
                                    persistentId:id,
                                    _token : '{!! csrf_token() !!}'
                                },
                                success:function (response) {
                                    if (response.length&&response==1) {
                                        fun.call();
                                    } else if (response.length&&response==0) {
                                        alert('The fop is failed');
                                        return;
                                    } else{
                                        setTimeout(function () {
                                            get_prefop(id,fun,retries);
                                        }, 2000);
                                    }
                                },
                                error:function (err) {
                                    setTimeout(function () {
                                        get_prefop(id,fun,++retries);
                                    }, retries*1000);
                                }
                            })
                        }
                    }
                    setTimeout(function () {
                        get_prefop(info.persistentId,make);
                    }, 2000);
                },
                'Error': function(up, err, errTip) {
                    alert(errTip||err.message);
                },
                'Key': function(up, file) {
                    return file.key
                }
            }
        });
    </script>
@endsection
